package com.weixin.paleituo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.GoodsPreviewRecycleAdapter;
import com.weixin.paleituo.annotation.OrderCreatedType;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.CouponsBean;
import com.weixin.paleituo.bean.CreateOrderBody;
import com.weixin.paleituo.bean.GoodsSpecifBean;
import com.weixin.paleituo.bean.OrderCreatedBean;
import com.weixin.paleituo.bean.OrderGoods;
import com.weixin.paleituo.bean.OrderInvoiceBean;
import com.weixin.paleituo.bean.ShippingAddressBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.http.ApiException;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.MonitorScrollView;
import com.weixin.paleituo.view.ShopCarToastView;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * 订单创建页面
 * 看需求酌情考虑是否同步修改普通订单创建页面{@link CreateSharedOrderActivity }
 * 订单类型：定制订单、普通订单。
 * 定制订单：无优惠券相关操作；普通订单可使用优惠券
 * 地址类型：有默认地址、无默认地址
 *
 * @author fengzhen
 * @version v1.0, 2018/3/31
 */
public class CreateOrderActivity extends BasePersonActivity {

    public static final int REQUEST_ORDER_ADDRESS = 0x112;
    public static final int REQUEST_ORDER_COUPONS = 0x113;
    public static final int REQUEST_ORDER_INVOICE = 0x114;

    @BindView(R.id.stub_custom_tips_activity_create_order)
    android.view.ViewStub mStubCustomTipsActivityCreateOrder;
    @BindView(R.id.stub_surface_custom_tips_activity_create_order)
    android.view.ViewStub mStubSurfaceCustomTipsActivityCreateOrder;
    @BindView(R.id.stub_address_activity_create_order)
    android.view.ViewStub mStubAddressActivityCreateOrder;
    @BindView(R.id.stub_no_address_activity_create_order)
    android.view.ViewStub mStubNoAddressActivityCreateOrder;
    @BindView(R.id.stub_coupons_clearing_activity_create_order)
    android.view.ViewStub mStubCouponsClearingActivityCreateOrder;
    @BindView(R.id.stub_coupons_activity_create_order)
    android.view.ViewStub mStubCouponsActivityCreateOrder;
    @BindView(R.id.recycle_activity_create_order)
    RecyclerView mRecycleActivityCreateOrder;
    @BindView(R.id.tv_order_count_activity_create_order)
    TextView mTvOrderCountActivityCreateOrder;
    @BindView(R.id.tv_invoice_activity_create_order)
    TextView mTvInvoiceActivityCreateOrder;
    @BindView(R.id.tv_send_type_activity_create_order)
    TextView mTvSendTypeActivityCreateOrder;
    @BindView(R.id.stub_custom_order_activity_create_order)
    android.view.ViewStub mStubCustomOrderActivityCreateOrder;
    @BindView(R.id.edit_sum_activity_create_order)
    EditText mEditSumActivityCreateOrder;
    @BindView(R.id.relative_sum_activity_create_order)
    RelativeLayout mRelativeSumActivityCreateOrder;
    @BindView(R.id.edit_pay_express_activity_create_order)
    EditText mEditPayExpressActivityCreateOrder;
    @BindView(R.id.relative_pay_express_activity_create_order)
    RelativeLayout mRelativePayExpressActivityCreateOrder;
    @BindView(R.id.btn_commit_order_activity_create_order)
    Button mBtnCommitOrderActivityCreateOrder;
    @BindView(R.id.tv_pay_activity_create_order)
    TextView mTvPayActivityCreateOrder;
    @BindView(R.id.scroll_activity_create_order)
    MonitorScrollView mScrollActivityCreateOrder;

    private LoadingPagerHead mLoadingPagerHead;
    private DecimalFormat format = new DecimalFormat("#0.00");
    private DynamicLoadHolder mDynamicLoadHolder;

    // 订单类型 定制/普通 0/1
    private int mOrderType = 1;
    // 是否有地址 默认没有
    private boolean hasAddress = false;
    private boolean hasDefaultAddress = false;
    // 展示地址
    private ShippingAddressBean mCurrentAddress;
    // 优惠券字段
    private int mCouponsCount = 0;
    private boolean hasCoupons = true;
    private double mCouponsSum = 0.00;
    private ArrayList<CouponsBean> mChooseCoupons;
    private ArrayList<CouponsBean> mAllCoupons = new ArrayList<>();
    private int mDeductionCoupons;
    // 商品总金额
    private double mGoodsSum = 0.0;
    // 运费金额
    private double mExpressSum = 0.00;
    // 总金额
    private double mPaySum;
    // 商品list
    private ArrayList<OrderGoods> mGoodsList;
    private int mGoodsCount = 0;
    // 发票
    private OrderInvoiceBean mInvoice;
    private String mCustomContent;

    private GoodsPreviewRecycleAdapter mGoodsPreviewPicAdapter;

    /**
     * 跳转创建订单界面
     *
     * @param customContent 定制内容，如果为null，则为普通订单
     * @param goodsList     商品列表，包含所有必须数据
     */
    public static Intent call2CreateOrder(Context context, String customContent, ArrayList<OrderGoods> goodsList) {
        Intent intent = new Intent(context, CreateOrderActivity.class);
        intent.putExtra(Contans.INTENT_DATA, goodsList);
        intent.putExtra(Contans.INTENT_TYPE, customContent);
        return intent;
    }

    @Override
    protected View getContentView(final Context context) {
        mLoadingPagerHead = new LoadingPagerHead(context) {
            @Override
            protected void close() {
                onBackPressed();
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(CreateOrderActivity.this, R.layout.activity_create_order);
            }

            @Override
            protected void reLoading() {
                getCouponsAndAddress();
            }
        };
        return mLoadingPagerHead;
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED);
        finish();
    }

    @Override
    protected void initView() {
        super.initView();

        mDynamicLoadHolder = new DynamicLoadHolder(this);
        Intent intent = getIntent();
        mGoodsList = (ArrayList<OrderGoods>) intent.getSerializableExtra(Contans.INTENT_DATA);
        mCustomContent = intent.getStringExtra(Contans.INTENT_TYPE);
        mOrderType = TextUtils.isEmpty(mCustomContent) ? OrderCreatedType.NORMAL : OrderCreatedType.CUSTOM;

        // 计算商品总金额  以及  优惠金额总量
        if (mGoodsList == null) {
            ToastUtils.makeText("商品信息异常！");
            finish();
            return;
        }
        if (1 == mOrderType) {
            BigDecimal decimal = new BigDecimal(0.0);
            BigDecimal sumDecimal = new BigDecimal(0.0);
            for (OrderGoods goods : mGoodsList) {
                decimal = decimal.add(new BigDecimal(goods.getCouponMoney()).multiply(new BigDecimal(goods.getCount())));
                if (goods.isVip()) {
                    sumDecimal = sumDecimal.add(new BigDecimal(goods.getSpecialSales()).multiply(new BigDecimal(goods.getCount())));
                } else {
                    sumDecimal = sumDecimal.add(new BigDecimal(goods.getPrice()).multiply(new BigDecimal(goods.getCount())));
                }
            }
            mDeductionCoupons = decimal.intValue();
            mGoodsSum = sumDecimal.doubleValue();
        } else {
            mGoodsSum = -1;
            mDeductionCoupons = 0;
            StringBuffer buffer = new StringBuffer();
            OrderGoods goods = mGoodsList.get(0);
            ArrayList<GoodsSpecifBean> goodsSpecsList = goods.getGoodsSpecsList();
            if (goodsSpecsList != null) {
                for (GoodsSpecifBean bean :
                        goodsSpecsList) {
                    buffer.append(bean.getId()).append("_");
                }
            }
            goods.setIdlist(buffer.toString());
        }
        for (OrderGoods goods :
                mGoodsList) {
            mGoodsCount += goods.getCount();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        mTvTitle.setText("填写订单");

        mInvoice = new OrderInvoiceBean();
        mInvoice.setType(1);
        mInvoice.setTitle(3);
        mInvoice.setInvoiceName("不开发票");
        mTvInvoiceActivityCreateOrder.setText(mInvoice.getInvoiceName());

        getCouponsAndAddress();
    }

    /**
     * 根据类型加载UI
     */
    private void initUIForType() {
        // 地址bar初始化
        refreshAddressBar();
        // 定制类型
        if (mOrderType == 0) {
            // 加载顶部tips
            mDynamicLoadHolder.loadBaseStub(mStubCustomTipsActivityCreateOrder, true);
            mDynamicLoadHolder.loadBaseStub(mStubSurfaceCustomTipsActivityCreateOrder, true);
            // 加载定制输入框
            mDynamicLoadHolder.loadCustomStub(mStubCustomOrderActivityCreateOrder);
        } else if (mOrderType == 1) {
            // 加载优惠券选择模块
            mDynamicLoadHolder.loadCouponsStub(mStubCouponsActivityCreateOrder, mCouponsCount, hasCoupons, mCouponsSum);
            // 加载优惠券结算展示
            mDynamicLoadHolder.loadCouponsClearingStub(mStubCouponsClearingActivityCreateOrder, mCouponsSum);
        }

        mRecycleActivityCreateOrder.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        mGoodsPreviewPicAdapter = new GoodsPreviewRecycleAdapter(this, mGoodsList);
        mRecycleActivityCreateOrder.setAdapter(mGoodsPreviewPicAdapter);
        mTvOrderCountActivityCreateOrder.setText(String.format(getString(R.string.string_count_goods), mGoodsCount));

        if (mGoodsSum > 0) {
            mEditSumActivityCreateOrder.setText(String.format(getString(R.string.string_pay), format.format(mGoodsSum)));
        } else {
            mEditSumActivityCreateOrder.setText("待定");
        }
        mEditPayExpressActivityCreateOrder.setText(String.format(getString(R.string.string_add_pay), format.format(mExpressSum)));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                /**
                 * 处理地址回传信息，更新订单地址
                 */
                case REQUEST_ORDER_ADDRESS:
                    mCurrentAddress = data.getParcelableExtra(Contans.INTENT_DATA);
                    hasDefaultAddress = true;
                    refreshAddressBar();
                    break;

                /**
                 * 处理优惠券回传信息，更新界面展示
                 */
                case REQUEST_ORDER_COUPONS:
                    mChooseCoupons = (ArrayList<CouponsBean>) data.getSerializableExtra(Contans.INTENT_DATA);
                    double extra = data.getDoubleExtra(Contans.INTENT_EXTRA, 0.0);
                    mCouponsSum = extra > mDeductionCoupons ? mDeductionCoupons : extra;
                    if (mChooseCoupons == null || mChooseCoupons.size() <= 0) {
                        mCouponsCount = 0;
                        mCouponsSum = 0;
                    } else {
                        mCouponsCount = mChooseCoupons.size();
                    }
                    mDynamicLoadHolder.loadCouponsStub(mStubCouponsActivityCreateOrder, mCouponsCount, hasCoupons, mCouponsSum);
                    mDynamicLoadHolder.loadCouponsClearingStub(mStubCouponsClearingActivityCreateOrder, mCouponsSum);
                    break;

                /**
                 * 处理发票回传信息，更新界面展示
                 */
                case REQUEST_ORDER_INVOICE:
                    mInvoice = data.getParcelableExtra(Contans.INTENT_DATA);
                    mTvInvoiceActivityCreateOrder.setText(mInvoice.getInvoiceName());
                    break;
            }
        }
    }

    /**
     * 更新实付款数额
     */
    private void refreshPay() {
        if (mGoodsSum >= 0) {
            BigDecimal paySum = new BigDecimal(mGoodsSum)
                    .subtract(new BigDecimal(mExpressSum))
                    .subtract(new BigDecimal(mCouponsSum));
            mPaySum = paySum.doubleValue();
            mTvPayActivityCreateOrder.setText(getString(R.string.string_pay, format.format(mPaySum)));
        } else {
            mTvPayActivityCreateOrder.setText("待定");
        }
    }

    /**
     * 刷新地址展示barUI
     */
    private void refreshAddressBar() {
        mDynamicLoadHolder.loadNoAddressStub(mStubNoAddressActivityCreateOrder, hasAddress, !hasDefaultAddress);
        mDynamicLoadHolder.loadAddressStub(mStubAddressActivityCreateOrder, mCurrentAddress, hasDefaultAddress);
    }

    /**
     * 获取创建订单信息
     *
     * @author fengzhen
     * @version v1.0, 2018/3/31
     */
    private void getCouponsAndAddress() {
        mLoadingPagerHead.showPagerView(Contans.STATE_LOADING);
        Observable<StatusCode<List<ShippingAddressBean>>> observable = ApiUtils.getApi().getCouponsForOrder(
                BaseApplication.getToken(), BaseApplication.getUserId(), null, String.valueOf(mDeductionCoupons)
        ).flatMap(new Function<StatusCode<List<CouponsBean>>, ObservableSource<StatusCode<List<ShippingAddressBean>>>>() {
            @Override
            public ObservableSource<StatusCode<List<ShippingAddressBean>>> apply(StatusCode<List<CouponsBean>> stringStatusCode) throws Exception {
                List<CouponsBean> data = stringStatusCode.getData();
                mAllCoupons.addAll(data);
                if (data == null) {
                    return Observable.error(new ApiException("优惠券异常"));
                } else {
                    hasCoupons = data.size() > 0;
                }
                return ApiUtils.getApi().getShippingAddress(BaseApplication.getToken(), BaseApplication.getUserId());
            }
        });

        HttpUtil.getInstance().toSubscribe(observable,
                new ProgressSubscriber<List<ShippingAddressBean>>(this) {

                    @Override
                    protected void _onNext(StatusCode<List<ShippingAddressBean>> listStatusCode) {
                        mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                        if (listStatusCode.getData().size() <= 0) {
                            mCurrentAddress = null;
                            hasDefaultAddress = false;
                            hasAddress = false;
                        } else {
                            mCurrentAddress = null;
                            hasAddress = true;
                            hasDefaultAddress = false;
                            for (ShippingAddressBean address :
                                    listStatusCode.getData()) {
                                if (address.isdefault()) {
                                    mCurrentAddress = address;
                                    hasDefaultAddress = true;
                                }
                            }
                        }
                        initUIForType();
                    }

                    @Override
                    protected void _onError(String message) {
                        mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);
                        ToastUtils.makeText(message);
                    }
                }, "", lifecycleSubject, false, true);
    }

    /**
     * 提交订单
     */
    private void commitOrder() {

        if (mCurrentAddress == null) {
            ShopCarToastView shopCarToastView = new ShopCarToastView(this);
            shopCarToastView.setIcon(R.mipmap.address_error);
            shopCarToastView.setText("您还没有选择收获地址哦");
            shopCarToastView.setDuration(Toast.LENGTH_LONG);
            shopCarToastView.show();
            return;
        }

        CreateOrderBody createOrderBody = new CreateOrderBody();

        createOrderBody.setToken(BaseApplication.getToken());
        createOrderBody.setUserId(BaseApplication.getUserId());
        createOrderBody.setOrderType("android");
        createOrderBody.setMadeType(mOrderType + 1);
        createOrderBody.setTotalPrice(new BigDecimal(mGoodsSum));
        createOrderBody.setTotalCouponMoney((int) mCouponsSum);
        createOrderBody.setTransport("免邮");
        createOrderBody.setUserAddress(mCurrentAddress.getId());
        createOrderBody.setInvoice(mInvoice);
        createOrderBody.setCouponHistorys(mChooseCoupons);

        if (mOrderType == 1) {
            createOrderBody.setGoods(mGoodsList);
        } else if (mOrderType == 0) {
            String customInfo = mDynamicLoadHolder.getCustomInfo();
            if (TextUtils.isEmpty(customInfo)) {
                ToastUtils.makeText("定制信息不能为空");
                return;
            }
            createOrderBody.setGood(mGoodsList.get(0));
            createOrderBody.setMsg(customInfo);
        }

        showLoadingDialog();
        Observable<StatusCode<OrderCreatedBean>> createOrderObservable = ApiUtils.getApi().createGoodsOrder(createOrderBody);
        HttpUtil.getInstance().toSubscribe(createOrderObservable, new ProgressSubscriber<OrderCreatedBean>(this) {
            @Override
            protected void _onNext(StatusCode<OrderCreatedBean> statusCode) {
                OrderCreatedBean data = statusCode.getData();
                dismissLoadingDialog();
                if (mOrderType == 1) {
                    startActivity(CheckstandActivity.call2CheckstandActivity(CreateOrderActivity.this, mOrderType, data));
                } else if (mOrderType == 0) {
                    MyOrderActivity.startActivity(CreateOrderActivity.this, BaseApplication.getUserId(), 1);
                }
                finish();
            }

            @Override
            protected void _onError(String message) {
                dismissLoadingDialog();
                ToastUtils.makeText(message);
            }
        }, "", lifecycleSubject, false, true);

    }

    @OnClick({R.id.tv_order_count_activity_create_order, R.id.tv_invoice_activity_create_order, R.id.btn_commit_order_activity_create_order})
    public void onClickM(View view) {
        switch (view.getId()) {

            /**
             * 跳转预览商品清单界面
             */
            case R.id.tv_order_count_activity_create_order:
                startActivity(GoodsListPreActivity.call2GoodsListPreActivity(this, mGoodsList));
                break;

            /**
             *  跳转发票信息界面
             */
            case R.id.tv_invoice_activity_create_order:
                startActivityForResult(OrderInvoiceActivity.call2OrderInvoiceActivity(this, mInvoice), REQUEST_ORDER_INVOICE);
                break;

            /**
             *  提交订单
             */
            case R.id.btn_commit_order_activity_create_order:
                commitOrder();
                break;
        }
    }

    /**
     * 价格信息发生变化，更新总金额信息
     */
    @OnTextChanged(callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED,
            value = {R.id.edit_sum_activity_create_order, R.id.edit_pay_express_activity_create_order})
    public void afterPayChanged(Editable e) {
        refreshPay();
    }

    /**
     * ViewStub同意加载holder
     *
     * @author fengzhen
     * @version v1.0, 2018/3/31
     */
    private class DynamicLoadHolder {
        private Context mContext;
        private EditText mEditCustomInfo;

        public DynamicLoadHolder(Context context) {
            this.mContext = context;
        }

        String getCustomInfo() {
            if (mEditCustomInfo != null) {
                return mEditCustomInfo.getText().toString();
            }
            return null;
        }

        /**
         * 加载展示类ViewStub
         * 包含：浮动定制订单tab、固定定制订单tab
         *
         * @param visible 是否可见 true：可见
         */
        void loadBaseStub(@NonNull ViewStub viewStub, boolean visible) {
            View inflate = null;
            try {
                if (visible) {
                    inflate = viewStub.inflate();
                    viewStub.setTag(inflate);
                }
            } catch (Exception e) {
                inflate = (View) viewStub.getTag();
            } finally {
                viewStub.setVisibility(visible ? View.VISIBLE : View.GONE);
            }
        }

        /**
         * 加载定制输入框ViewStub
         */
        void loadCustomStub(@NonNull ViewStub viewStub) {
            View inflate = null;
            try {
                inflate = viewStub.inflate();
                viewStub.setTag(inflate);
                mEditCustomInfo = inflate.findViewById(R.id.edit_custom_content_activity_create_order);
                // 解决滑动冲突事件
                mEditCustomInfo.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (canVerticalScroll(mEditCustomInfo)) {
                            v.getParent().requestDisallowInterceptTouchEvent(true);
                            if (event.getAction() == MotionEvent.ACTION_UP) {
                                v.getParent().requestDisallowInterceptTouchEvent(false);
                            }
                        }
                        return false;
                    }
                });
                mEditCustomInfo.setImeOptions(EditorInfo.IME_ACTION_DONE);
                mEditCustomInfo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            //ToastUtils.makeText("关闭软键盘");
                        }
                        return false;
                    }
                });
                mEditCustomInfo.setText(mCustomContent);
            } catch (Exception e) {
                inflate = (View) viewStub.getTag();
                viewStub.setVisibility(View.VISIBLE);
            }
        }

        /**
         * 加载无默认地址tab，跳转进行添加地址/选择非默认地址使用
         * 一个地址都没有：跳转添加界面
         * 有非默认地址：跳转地址列表界面
         */
        void loadNoAddressStub(@NonNull ViewStub viewStub, final boolean hasAddress, boolean visible) {
            View inflate = null;
            try {
                if (visible) {
                    inflate = viewStub.inflate();
                    viewStub.setTag(inflate);
                    inflate.findViewById(R.id.relative_layout_no_order_address).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!hasAddress) {
                                // 一个地址都没有，跳添加地址
                                ((Activity) mContext).startActivityForResult(
                                        NewShippingAddressActivity.call2NewShippingAddressActivity(mContext, NewShippingAddressActivity.TYPE_NEW_USE),
                                        REQUEST_ORDER_ADDRESS);
                            } else {
                                // 没有默认地址，有非默认地址，跳地址管理界面
                                ((Activity) mContext).startActivityForResult(
                                        ManagerAddressActivity.call2AddressManagerActivity(mContext, ManagerAddressActivity.TYPE_FROM_ORDER, -1),
                                        REQUEST_ORDER_ADDRESS);
                            }
                        }
                    });
                }
            } catch (Exception e) {
                inflate = (View) viewStub.getTag();
            } finally {
                viewStub.setVisibility(visible ? View.VISIBLE : View.GONE);
            }
        }

        /**
         * 加载默认物流地址，点击跳转选择地址界面
         * 将页面赋值放在最后，保证每一次调用都会更新UI展示
         */
        void loadAddressStub(@NonNull ViewStub viewStub, ShippingAddressBean address, boolean visible) {
            View inflate = null;
            try {
                if (visible) {
                    inflate = viewStub.inflate();
                    viewStub.setTag(inflate);
                    inflate.findViewById(R.id.relative_layout_order_address).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ((Activity) mContext).startActivityForResult(
                                    ManagerAddressActivity.call2AddressManagerActivity(
                                            mContext, ManagerAddressActivity.TYPE_FROM_ORDER, mCurrentAddress == null ? -1 : mCurrentAddress.getId()),
                                    REQUEST_ORDER_ADDRESS);
                        }
                    });
                }
            } catch (Exception e) {
                inflate = (View) viewStub.getTag();
            } finally {
                viewStub.setVisibility(visible ? View.VISIBLE : View.GONE);
                if (visible && address != null) {
                    // 页面赋值放最后保证刷新界面
                    TextView tvUser = inflate.findViewById(R.id.tv_user_layout_order_address);
                    tvUser.setText(address.getContact());
                    TextView tvPhone = inflate.findViewById(R.id.tv_tel_layout_order_address);
                    tvPhone.setText(address.getPhone());
                    View imgDefault = inflate.findViewById(R.id.img_default_layout_order_address);
                    imgDefault.setVisibility(address.isdefault() ? View.VISIBLE : View.GONE);
                    TextView tvAddress = inflate.findViewById(R.id.tv_address_layout_order_address);
                    tvAddress.setText(address.getDetailAddress());
                }
            }
        }

        /**
         * 加载优惠券选择tab
         * 同时根据优惠券信息刷新UI
         *
         * @param count      优惠券数量
         * @param hasCoupons 是否有优惠券
         * @param deduction  抵扣数量
         */
        void loadCouponsStub(@NonNull ViewStub stub, int count, final boolean hasCoupons, double deduction) {
            View inflate = null;
            try {
                inflate = stub.inflate();
                stub.setTag(inflate);
            } catch (Exception e) {
                inflate = (View) stub.getTag();
                inflate.setVisibility(View.VISIBLE);
            } finally {
                TextView couponsTag = inflate.findViewById(R.id.tv_tag_coupons_activity_create_order);
                if (count > 0) {
                    couponsTag.setText(String.format(mContext.getString(R.string.string_count_coupons), count));
                    couponsTag.setVisibility(View.VISIBLE);
                } else {
                    couponsTag.setVisibility(View.GONE);
                }
                TextView tvDeduction = inflate.findViewById(R.id.tv_deduction_coupon_activity_create_order);
                if (hasCoupons) {
                    inflate.findViewById(R.id.relative_coupons_activity_create_order).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (hasCoupons) {
                                ((Activity) mContext).startActivityForResult(
                                        SelectorCouponsActivity.call2SelectorCouponsActivity(mContext, mAllCoupons, mChooseCoupons),
                                        REQUEST_ORDER_COUPONS);
                            }
                        }
                    });
                    if (count > 0) {
                        tvDeduction.setText(String.format(mContext.getString(R.string.string_sub_pay), format.format(deduction)));
                    } else {
                        tvDeduction.setText("未选择");
                    }
                    tvDeduction.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(mContext, R.mipmap.ck), null);
                } else {
                    tvDeduction.setText("无可用");
                    tvDeduction.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                }
            }
        }

        /**
         * 加载优惠券抵扣详情tab
         *
         * @param deduction 优惠券抵扣金额
         */
        void loadCouponsClearingStub(@NonNull ViewStub stub, double deduction) {
            View inflate = null;
            try {
                inflate = stub.inflate();
                stub.setTag(inflate);
            } catch (Exception e) {
                inflate = (View) stub.getTag();
                stub.setVisibility(View.VISIBLE);
            } finally {
                EditText editCouponsDeduction = inflate.findViewById(R.id.tv_coupon_activity_create_order);
                editCouponsDeduction.setText(String.format(mContext.getString(R.string.string_sub_pay), format.format(deduction)));
                editCouponsDeduction.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        refreshPay();
                    }
                });
            }
        }

        /**
         * EditText竖直方向是否可以滚动
         *
         * @param editText 需要判断的EditText
         * @return true：可以滚动  false：不可以滚动
         */
        boolean canVerticalScroll(EditText editText) {
            //滚动的距离
            int scrollY = editText.getScrollY();
            //控件内容的总高度
            int scrollRange = editText.getLayout().getHeight();
            //控件实际显示的高度
            int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
            //控件内容总高度与实际显示高度的差值
            int scrollDifference = scrollRange - scrollExtent;
            if (scrollDifference == 0) {
                return false;
            }
            return (scrollY > 0) || (scrollY < scrollDifference - 1);
        }
    }
}
